package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.UserInfoDao;
import entity.SalesRecord;

/**
 * Servlet implementation class SalesRecordServlet
 */
@WebServlet("/SalesRecordServlet")
public class SalesRecordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SalesRecordServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String userIdParam = request.getParameter("userID");
        String memberLevel = request.getParameter("memberLevel");
        
        if (userIdParam!= null) {
            try {
                int userId = Integer.parseInt(userIdParam);
                UserInfoDao userInfoDao = new UserInfoDao();
                List<SalesRecord> salesRecords = userInfoDao.getSalesRecordsByUserId(userId,memberLevel);
                request.setAttribute("salesRecords", salesRecords);
                request.getRequestDispatcher("record.jsp").forward(request, response);
            } catch (NumberFormatException e) {
                // 处理用户ID参数转换整数失败的情况，比如参数格式不对
                response.getWriter().write("用户ID参数格式不正确，请检查");
                return;
            } catch (SQLException e) {
                // 更合理地处理数据库查询异常情况，比如记录日志等，这里简单返回友好错误提示给前端
                e.printStackTrace();
                response.getWriter().write("获取消费记录时出现数据库异常，请联系管理员");
                return;
            }
        } else {
            response.getWriter().write("未获取到有效的用户编号参数，请检查请求");
            return;
        }
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
